package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @PostMapping
    public R<String>save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return  R.success("添加菜品成功！");
    }
    @GetMapping("/page")
    public R<Page>page(Integer page,Integer pageSize,String name){
        //定义分页对象
        Page<Dish>dishPage=new Page<>(page,pageSize);
        //加入模糊查询条件
        LambdaQueryWrapper<Dish> wrapper= new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //完成查询
        dishService.page(dishPage,wrapper);
      //将每个Dish转成DishDto对象
        List<Dish> dishes = dishPage.getRecords();
        //定义DishDto的分页对象
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);
        //创建一个集合，用于存储所有DisDto的对象们
        List<DishDto> DishDtos = new ArrayList<>();
        //转换：将每一个dishes中的dish，转成DishDtos中的对象
        for (Dish dish : dishes) {
            DishDto dishDto = new DishDto();
            //赋值每个Dish的所有字段到DishDto中
            BeanUtils.copyProperties(dish,dishDto);
            //从dish对象中获取分类id：categoryId
            Long categoryId = dish.getCategoryId();
            //通过分类id获取分类对象
            Category categoryServiceForName = categoryService.getById(categoryId);
            //从分类对象中获取分类名称，赋值给DishDto中的categoryName属性
            dishDto.setCategoryName(categoryServiceForName.getName());
            //将赋值了成员变量的disDto对象放入disDto的集合中
              DishDtos.add(dishDto);
        }
                //将disDto集合，放入page<DisDto>中，作为分页数据
               dishDtoPage.setRecords(DishDtos);
          //将之前查询到得total数据防到dto的page中
        dishDtoPage.setTotal(dishPage.getTotal());
        return  R.success(dishDtoPage);

    }
    @GetMapping("/{id}")
    public R<DishDto>get(@PathVariable Long  id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }
    //修改
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }
    //根据分类查询菜品
    @GetMapping("/list")
    public R<List<DishDto>>list(Dish dish){
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1(起售状态)的菜品
        wrapper.eq(Dish::getStatus,1);
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(wrapper);
        List<DishDto>dishDtos=list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                String name = category.getName();
                dishDto.setCategoryName(name);
            }
           //当前菜品的id
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(DishFlavor::getDishId,id);
            List<DishFlavor> list1 = dishFlavorService.list(wrapper1);
            dishDto.setFlavors(list1);
           return  dishDto;

        }).collect(Collectors.toList());

        //当前菜品的id

        return  R.success(dishDtos);

    }
    /**
     * 根据id(批量)停售菜品信息
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateMulStatus(@PathVariable Integer status, Long[] ids){
        List<Long> list = Arrays.asList(ids);
        //构造条件构造器
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        //添加过滤条件
        updateWrapper.set(Dish::getStatus,status).in(Dish::getId,list);
        dishService.update(updateWrapper);

        return R.success("菜品信息修改成功");
    }


}
